/*
 *
 *
Copyright (c) 1998-2001 Aristar, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:

"This product includes software developed by Aristar, Inc. (http://www.aristar.com/)."

Alternately, this acknowledgment may appear in the software itself, if and
wherever such third-party acknowledgments normally appear.

4. The names "Dialect" and "Aristar, Inc." must not be used to endorse or
promote products derived from this software without prior written permission.
For written permission, please contact info@aristar.com.

5. Products derived from this software may not be called "Dialect", nor may
"Dialect" appear in their name, without prior written permission of Aristar, Inc.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
ARISTAR, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software consists of voluntary contributions made by many individuals
on behalf of Aristar, Inc.  For more information on Aristar, Inc.,
please see <http://www.aristar.com/>.

Portions of this software are based upon software freely available and
written by individuals not associated with Aristar, Inc.  Copyrights are
maintained in the relevant source code files.
 *
 *
 */

// QMenuBar.cpp : implementation file
//

#include "stdafx.h"
#include "QMenuBar.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define KICK_TIMER	34234

/////////////////////////////////////////////////////////////////////////////

static long WndToMenuCount = 0;
VALUE g_vWndToMenu;	// CQwindow needs this for WM_SYSCHAR handling

static void StoreWndToMenu(CWnd* pRootWnd, CQMenuBar* pMenubar)
{
	InterlockedIncrement(&WndToMenuCount);
	if (g_vWndToMenu.Type() != stFrame) {
		g_vWndToMenu = AllocFrame();
	}

	CString temp;
	temp.Format(_T("%d"), (int)pRootWnd);
	g_vWndToMenu.Set(temp, (int)pMenubar);
}

static void RemoveWndToMenu(CWnd* pRootWnd, CQMenuBar* pMenubar)
{
	CString temp;
	temp.Format(_T("%d"), (int)pRootWnd);
	if (g_vWndToMenu.Get(temp).Integer() == (int)pMenubar) {
		g_vWndToMenu.Set(temp, AllocNil());
	}

	InterlockedDecrement(&WndToMenuCount);
	if (WndToMenuCount == 0) {
		g_vWndToMenu = AllocNil();
	}
}

/////////////////////////////////////////////////////////////////////////////
// CQMenuBar

class CMenuItem {
public:
	CMenuItem(){hotKey = '\0'; vMenu = AllocNil();}
	CString text;
	TCHAR hotKey;
	VALUE vMenu;
	CRect rc;
};

CQMenuBar::CQMenuBar(CQWindow* pQWindow, RECT& rc, VALUE vMenuData,
					 BorderStyle borderStyle,
					 VALUE (*pHandler)(CQMenuBar*, int, VALUE), VALUE vSelf)
					:CWnd(), CQBase(vSelf)
{
	ASSERT(m_pRootParent != NULL);

	m_BorderStyle = borderStyle;
	m_pHandler = pHandler;
	Create(NULL, NULL, WS_VISIBLE | WS_CHILD, rc, pQWindow, 0);

	// m_pRootParent will be the window that receives WM_SYSCHAR messages
	m_pRootParent = pQWindow;
	CWnd *p = m_pRootParent->GetParent();
	while (p != NULL) {
		m_pRootParent = p;
		p = m_pRootParent->GetParent();
	}

	StoreWndToMenu(m_pRootParent, this);

	m_vMenuData = vMenuData.DeepClone();

	if ((m_vMenuData.Type() != stArray) || (m_vMenuData.Length() == 0)) {
		m_MenuLabels = NULL;
	}
	else {
		int numItems = m_vMenuData.Length();
		m_MenuLabels = new CMenuItem[numItems];

		int left = 5;
		CDC* pDC = GetDC();
		CFont* oldFont = pDC->SelectObject(&g_QLabelFont);

		for (int idx = 0; idx < numItems; ++idx) {
			VALUE vArray = m_vMenuData[idx + 1];
			if ((vArray.Type() != stArray) || (vArray.Length() != 2)) {
				continue;	// Bad item, skip it
			}
			CSize extent = pDC->GetTextExtent(vArray[1].String());
			m_MenuLabels[idx].text = vArray[1].String();
			m_MenuLabels[idx].vMenu = vArray[2];
			m_MenuLabels[idx].hotKey = FindHotKey(vArray[1].String());
			m_MenuLabels[idx].rc = CRect(left, 5, left + extent.cx, 5 + extent.cy);
			left += 5 + extent.cx;
		}
		pDC->SelectObject(oldFont);
		ReleaseDC(pDC);
	}
}

CQMenuBar::~CQMenuBar()
{
	RemoveWndToMenu(m_pRootParent, this);
	delete[] m_MenuLabels;
}


BEGIN_MESSAGE_MAP(CQMenuBar, CWnd)
	//{{AFX_MSG_MAP(CQMenuBar)
	ON_WM_DESTROY()
	ON_WM_SIZE()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_PAINT()
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CQMenuBar message handlers

void CQMenuBar::OnDestroy()
{
	CWnd::OnDestroy();
	if (m_pHandler) m_pHandler(this, QW_DESTROY, VALUE());	// Causes garbage collection
}

void CQMenuBar::SetBorderStyle(BorderStyle b)
{
	m_BorderStyle = b;
	InvalidateRect(NULL);
}

CQMenuBar::BorderStyle CQMenuBar::GetBorderStyle()
{
	return m_BorderStyle;
}

TCHAR CQMenuBar::FindHotKey(CString text)
{
	for (int idx = 0; idx < text.GetLength() - 1; ++idx) {
		if (text[idx] == '&') {
			TCHAR ch = text[idx + 1];
			if ((ch >= 'A') && (ch <= 'Z')) {
				// Make sure it's lower case
				ASSERT('a' > 'A');
				ch = ch + 'a' - 'A';
			}
			return ch;
		}
	}
	return '\0';
}

bool CQMenuBar::DoSysChar(TCHAR charCode)
{
	if ((charCode >= 'A') && (charCode <= 'Z')) {
		// Make sure it's lower case
		ASSERT('a' > 'A');
		charCode = charCode + 'a' - 'A';
	}

	for (int idx = 0; idx < m_vMenuData.Length(); ++idx) {
		if (m_MenuLabels[idx].hotKey == charCode) {
			DisplayMenu(idx);
			return true;	// true == we processed the message
		}
	}
	return false;
}

BOOL CQMenuBar::PreTranslateMessage(MSG* pMsg)
{
	return CWnd::PreTranslateMessage(pMsg);
}

void CQMenuBar::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);

	// TODO: Add your message handler code here

}

BOOL CQMenuBar::OnCommand(WPARAM wParam, LPARAM lParam)
{
	if ((lParam == 0) && (m_pHandler != NULL)) {
		// Menu item...
		if (m_vIdToValue.Type() == stFrame) {
			CString temp;
			temp.Format(_T("%d"), (int)wParam);
			VALUE v = m_vIdToValue.Get(temp);
			if (m_pHandler) m_pHandler(this, QW_MENUSELECT, v);
			return TRUE;
		}
	}
	return CWnd::OnCommand(wParam, lParam);
}

void CQMenuBar::OnLButtonDown(UINT nFlags, CPoint point)
{
	for (int idx = 0; idx < m_vMenuData.Length(); ++idx) {
		int x = point.x;
		if ((x >= m_MenuLabels[idx].rc.left) && (x <= m_MenuLabels[idx].rc.right)) {
			DisplayMenu(idx);
			break;
		}
	}
}

void CQMenuBar::OnLButtonUp(UINT nFlags, CPoint point)
{
	// TODO: Add your message handler code here and/or call default

	CWnd::OnLButtonUp(nFlags, point);
}

void CQMenuBar::OnPaint()
{
	CPaintDC dc(this); // device context for painting

	RECT rc;
	GetClientRect(&rc);
	dc.FillSolidRect(&rc, GetSysColor(COLOR_BTNFACE));

	CFont* oldFont = dc.SelectObject(&g_QLabelFont);
	dc.SetBkMode(TRANSPARENT);
	for (int idx = 0; idx < m_vMenuData.Length(); ++idx) {
		dc.DrawText(m_MenuLabels[idx].text, m_MenuLabels[idx].rc, DT_CENTER);
	}
	dc.SelectObject(oldFont);

	if (m_BorderStyle == bsRaised) {
		dc.Draw3dRect(&rc, RGB(255, 255, 255), RGB(0, 0, 0));
	}
	else if (m_BorderStyle == bsSunken) {
		dc.Draw3dRect(&rc, RGB(0, 0, 0),  RGB(255, 255, 255));
	}
	else if (m_BorderStyle == bsLine) {
		CBrush brush;
		brush.CreateSolidBrush(RGB(0, 0, 0));
		CBrush* pOldBrush = dc.SelectObject(&brush);
		dc.FrameRect(&rc, &brush);
		dc.SelectObject(pOldBrush);
	}
}

void CQMenuBar::DisplayMenu(int menuIndex)
{
	if ((menuIndex < 0) || (menuIndex >= m_vMenuData.Length())) return;

	VALUE vMenu;
	if (m_pHandler) {
		vMenu = m_pHandler(this, QW_INITMENU, m_MenuLabels[menuIndex].text);
		if (vMenu.Type() != stArray) {
			// Use popup menu from the constructor
			vMenu = m_MenuLabels[menuIndex].vMenu;
		}
	}

	if ((vMenu.Type() != stArray) || (vMenu.Length() == 0)) return;

	int len = vMenu.Length();
	m_PopupMenu.DestroyMenu();
	m_PopupMenu.CreatePopupMenu();
	m_vIdToValue = AllocFrame();

	VALUE theEntry;
	float count = 0.0;
	for (int k = 1; k <= len; k++)
	{
		DWORD mb = 0;
#ifdef UNDER_CE
		if (count>=11.5)
		{
			mb = MF_MENUBARBREAK;
			count = 0.0;
		}
#endif
		UINT options = 0;
		theEntry = vMenu[k];	// theList -> [["one", 1], ["two", 2, {enabled:false}]]
		if ((theEntry.Type() == stArray) && (theEntry.Length() > 0)) {
			if (theEntry.Length() == 3) {
				VALUE v = theEntry[3][_T("enabled")];
				if (v.Type() != stUndefined) {
					if (v.Boolean()) options |= MF_ENABLED;
					else options |= MF_GRAYED;
				}
				v = theEntry[3][_T("checked")];
				if (v.Type() != stUndefined) {
					if (v.Boolean()) options |= MF_CHECKED;
				}
			}

			CString temp;
			temp.Format(_T("%d"), k);
			m_vIdToValue.Set(temp, theEntry[2]);	// The value to return for this item

			theEntry = theEntry[1];	// Just want the actual menu item text
		}
		else {
			CString temp;
			temp.Format(_T("%d"), k);
			m_vIdToValue.Set(temp, theEntry);	// The value to return for this item
		}

		if (theEntry.Type() == stString)
		{
			CString entry = theEntry.String();
			if (entry==_T("-")) {
				::AppendMenu(m_PopupMenu.m_hMenu, mb | MF_SEPARATOR,0,_T(""));
				count += 0.5;
			}
			else {
				::AppendMenu(m_PopupMenu.m_hMenu, mb | MF_STRING | options,k,entry);
				count += 1.0;
			}
		}
	}

	// The x and y coordinates are in client, convert to screen
	CPoint pt(m_MenuLabels[menuIndex].rc.left, m_MenuLabels[menuIndex].rc.bottom);
	ClientToScreen(&pt);

#ifdef UNDER_CE
	// Until I find a good way to make the left/right arrow
	// keys work correctly for the menu bar on CE, just do this
	m_PopupMenu.TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this);
#else
	PostMessage(WM_SYSKEYDOWN, VK_DOWN, 1);
	PostMessage(WM_SYSKEYUP, VK_DOWN, 1);

	m_NextMenu = -1;
	m_CurrentMenu = menuIndex;
	SetTimer(KICK_TIMER, 50, NULL);
	m_PopupMenu.TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this);
	KillTimer(KICK_TIMER);
	m_CurrentMenu = -1;

	if (m_NextMenu >= 0) {
		DisplayMenu(m_NextMenu);
	}
#endif
}

void CQMenuBar::OnTimer(UINT nIDEvent)
{
	static bool bLeftLast = false;
	static bool bRightLast = false;

	if (nIDEvent == KICK_TIMER) {
		bool bLeft = GetAsyncKeyState(VK_LEFT) & 0x8000;
		bool bRight = GetAsyncKeyState(VK_RIGHT) & 0x8000;

		if (bLeft && !bLeftLast) {
			m_NextMenu = m_CurrentMenu - 1;
		}
		else if (bRight && !bRightLast) {
			m_NextMenu = m_CurrentMenu + 1;
		}

		if ((m_NextMenu < 0) || (m_NextMenu >= m_vMenuData.Length())) {
			m_NextMenu = -1;
		}
		else {
			PostMessage(WM_CANCELMODE);	// Kill current popup
			KillTimer(KICK_TIMER);
			//DisplayMenu(m_NextMenu);
			//GetFocus()->PostMessage(WM_SYSKEYDOWN, VK_ESCAPE, 1);
			//GetFocus()->PostMessage(WM_SYSKEYUP, VK_ESCAPE, 1);
			//PostThreadMessage(GetCurrentThreadId(), WM_KEYDOWN, VK_ESCAPE, 1);
			//PostThreadMessage(GetCurrentThreadId(), WM_KEYUP, VK_ESCAPE, 1);
		}

		bLeftLast = bLeft;
		bRightLast = bRight;
	}
}
